import store from '@/store'
import router from '@/router'
import { getKey } from '@/utils/storage'
import { connectWebSocket } from '@/utils/socket'
import { whiteList } from '@/utils/whiteList'

const token = whiteList ?? whiteList
console.log(token)
const permission = async (to, from, next) => {
  document.title = to.meta.title
  // 跳转的路由是否在白名单内
  if (whiteList.includes(to.path)) {
    next()
  } else {
    // 本地没有存储登录信息
    if (!getKey('tokenName') || !getKey('tokenValue')) {
      await router.push({
        path: '/login'
      })
    } else {
      // 查询是否有菜单信息，没有就进行获取菜单
      if (!store.state.layout.menuList.length) {
        await store.dispatch('setMenuDataAsync')
      }
      if (!store.state.user.userInfo) {
        await store.dispatch('getUserDetailAsync')
      }
      // 查询是否已经有websocket实例，没有就连接websocket
      if (!store.state.network.ws) {
        connectWebSocket()
      }
      if (to.path === '/projectDetailManage') {
        next()
        return
      }
      // 获取当前菜单是否有权限访问
      if (!store.state.layout.menuList.filter(item => {
        return item.name === to.name
      }).length) {
        // 如果当前有token信息，跳转到403
        if (getKey('tokenName') && getKey('tokenValue')) {
          next({
            path: '/403'
          })
        }
      } else {
        next()
      }
    }
  }
}
export default permission
